Classes and Methods: Some Notes#
If you don’t initialize the values of properties, the code will not compile. Initializing the values of properties inside the class is necessary.
Class variables#
The class variables
are shared by all instances or objects of the classes. A change in the class variable
will change the value of that property in all the objects of the class.
Instance variables#
The instance variables
are unique to each instance or object of the class. A change in the instance variable
will change the value of the property in that specific object only.
Method Overloading#
A method
can be made to preform different operations by overloading it. In Python, as opposed to C# for example, methods must be implicitly overloaded
.
Types of Methods#
Instance methods
, class methods
, and static methods
.
Class Methods#
Class methods
are accessed using the class name and not the object, and they don;t require an object to be created to be accessed.
We use the @classmethod
decorator, and we use cls
to refer to the class as we used self
to refer to the object.
Static Methods#
Static methods
are usually limited to the class only and not their objects. They can be used as utilities
for the class.
We use the @staticmethod
decorator and we don’t use a reference to the method, such as self
or cls
.
Static methods
have no knowledge of class variables or state, and so cannot modify class attributes.
Access Modifiers#
By default all methods and properties in a class are publicly available. Properties can be set to “private” by using the __
before the property name. Attempting to access this property will cause an error.